package com.zyl.mq.util;

import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeoutException;

/**
 * @author zyl
 * @Description
 * @since 2023/11/28 11:11
 */

public class RabbitMQUtils {

    /**
     * 向消息队列中发送消息
     * @param host
     * @param username
     * @param password
     * @param queueName
     * @param exchangeName
     * @param message
     */
    public static void sendMQMessage(String host, String username, String password , String queueName,  String exchangeName, String message) {
        ConnectionFactory factory = new ConnectionFactory();
        // 设置 RabbitMQ 主机地址
        factory.setHost(host);
        factory.setUsername(username);
        factory.setPassword(password);

        RabbitMQProducer rabbitMQUtil = new RabbitMQProducer(queueName, exchangeName);
        try {
            rabbitMQUtil.sendMessage(factory, message);
            System.out.println("队列名称：" + exchangeName);
        } catch (Exception e) {
            System.out.println("消息发送失败："+ e.getMessage());
        }
    }

    /**
     * 监听消息队列例子
     * @param host
     * @param username
     * @param password
     * @param queueName
     * @param messages
     */
    public static void waitTranscoding(String host, String username, String password , String queueName, String messages) {
        CountDownLatch latch = new CountDownLatch(1);
        //创建消费者
        RabbitMQSubscriber subscriber = new RabbitMQSubscriber(host, queueName,username,password);

        try {
            subscriber.startListening(message -> {
                if (message.contains(messages)){
                    // 如果消息包含文件 ID，释放 CountDownLatch
                    latch.countDown();
                }
            });
            try {
                //用于阻塞当前线程，直到计数器减为零
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                System.out.println("关闭连接");
                subscriber.close();
            } catch (IOException | TimeoutException e) {
                e.printStackTrace();
            }
        }
    }

}
